<!--
 * @Author: vera_min vera_min@163.com
 * @Date: 2025-08-22 00:49:17
 * @LastEditors: vera_min vera_min@163.com
 * @LastEditTime: 2025-08-26 16:10:07
 * @FilePath: /mail_project_destop/src/components/updateProcess/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog v-model="visible" title="下载进度" width="400px" center :show-close="false" :close-on-click-modal="false">
    <div class="process_con">
      <div class="process">
        <div class="process_bar" :style="{ width: `${updateProcess}%` }"></div>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { event } from '@tauri-apps/api';

const updateProcess = ref(0);
const visible = ref(false);

const isPoint = () => {
	const now = new Date();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();

	return (minutes === 0 && seconds <= 5) || (minutes === 59 && seconds > 55);
};

let isExecuted = false;
let lastCheckHour = -1;

// 手动检查更新
const manualCheckUpdate = () => {
    console.log('手动检查更新...');
    invoke('update_app', { token: localStorage.getItem('token') || '', force: false });
};

// 暴露给全局使用
(window as any).manualCheckUpdate = manualCheckUpdate;

const checkVersion = (force: boolean) => {
	// 判断是否处于正点附近（正点前后10秒范围内）
  const now = new Date();
  const currentHour = now.getHours();
  if (isPoint() || force) {
      // 避免重复执行
      if (!isExecuted || lastCheckHour !== currentHour || force) {
          console.log('开始检查更新...', { force, currentHour, lastCheckHour });
          invoke('update_app', { token: localStorage.getItem('token') || '', force: false });
          isExecuted = true;
          lastCheckHour = currentHour;
      }
  } else {
      // 如果不在正点附近，重置执行标志
      isExecuted = false;
  }
  // 改为每30秒检查一次，而不是10.5秒
	setTimeout(() => checkVersion(false), 30 * 1000);
};

const addUpdateListener = () => {
	event.listen('update-version-process', (process) => {
		updateProcess.value = process.payload as number;
    visible.value = true;
	});
	
	// 监听Rust后端日志
	event.listen('rust-log', (logEvent) => {
		console.log('[Rust后端]', logEvent.payload);
	});
};

// 页面加载时
onMounted(() => {
  addUpdateListener();
	checkVersion(true);
});

</script>
<style lang="scss" scoped>
.process_con {
  padding: 30px 40px;
  padding-top: 10px;
}

.process {
  height: 30px;
  background: #ddd;
}

.process_bar {
  background: #3B7AEE;
  height: 100%;
}
</style>
